import com.mit.web.business.proxy.MaintenanceProxy;
import com.mit.web.business.remote.IInvokeResponder;
import com.mit.web.config.Constants;
import com.mit.web.util.FlexSession;
import com.mit.web.util.FlexUtil;
import com.mit.web.util.LogUtil;
import com.mit.web.view.component.monitor.IProgressMonitor;
import com.mit.web.vo.maintenance.ProductTypeVO;

import mx.collections.ArrayCollection;
import mx.controls.ToolTip;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.logging.ILogger;
import mx.managers.ToolTipManager;
import mx.resources.ResourceManager;
import mx.rpc.events.ResultEvent;

[Bindable] private var _ds:ArrayCollection;

private var _pm:IProgressMonitor;
private var _proxy:MaintenanceProxy = MaintenanceProxy.getInstance();
private var _logger:ILogger;

private function init():void{
	_logger = LogUtil.getLogger(this);
	doRetrieve();
}

private function doRetrieve():void{
	var responder:IInvokeResponder = _proxy.getProductTypes().installProgressBar(_pm, this);	
	responder.addResultListener(retrieveListHandler);
	responder.addFaultListener(exceptionHandler);
}

private function retrieveListHandler(event:ResultEvent):void{
	_ds = event.result as ArrayCollection;
	for each(var o:Object in _ds){
		o.saveOriginal();
	}
	dg.validateNow();
}

private function doNew(event:MouseEvent):void{
	_ds.addItem(new ProductTypeVO()); 
	dg.validateNow();
	dg.editedItemPosition = {columnIndex:0, rowIndex:  _ds.length - 1};
}

private function doSave(event:MouseEvent):void{
	//Auto remove newly created empty record
	var clone:ArrayCollection = new ArrayCollection();
	clone = FlexUtil.deepClone(_ds) as ArrayCollection;
	for each(var o:Object in clone){
		if(o.id < 1 && (o.name == null || o.name == "") && (o.code == null || o.code == ""))
			_ds.removeItemAt(_ds.getItemIndex(o));
	}
	dg.validateNow();
	
	//validation to privent duplicate record
	//Why not validate when users focus out? because it will prevent users switching the name or  the code.
	if(!validate()){
		event.preventDefault();
		return;
	}
	
	//Only save items have changed
	var updateList:ArrayCollection = new ArrayCollection();
	for each(var type:Object in _ds){
		if(type.id < 1 || (type.name != type.original.name || type.code != type.original.code)){
			updateList.addItem(type);
		}else{
			_logger.debug("Item no change at " + type.name);
		}
	}
	//Save
	if(updateList.length > 0){
		var responder:IInvokeResponder = _proxy.updateProductTypes(updateList).installProgressBar(_pm, this);
		responder.addResultListener(savedHandler);
		responder.addFaultListener(exceptionHandler);
	}
}

private function savedHandler(event:ResultEvent):void{
	retrieveListHandler(event);
	showMessageTip(ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"info.common.saveOk"),  dg);
	
}

private function validate():Boolean{
	var clone:ArrayCollection = new ArrayCollection();
	clone = FlexUtil.deepClone(_ds) as ArrayCollection;
	for each(var o:Object in _ds){
		var id:int = o.id;
		var name:String = o.name;
		var code:String = o.code;
		var hasError:Boolean = false;
		var myError:String;
		if(name == null || name == ""){
			myError = ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"error.common.requiredField");
			dg.editedItemPosition = {columnIndex:1, rowIndex: _ds.getItemIndex(o)};
			hasError = true;
		}else if(code == null || code == "" ){
			myError = ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"error.common.requiredField");
			dg.editedItemPosition = {columnIndex:0, rowIndex: _ds.getItemIndex(o)};
			hasError = true;
		}
		
		if(!hasError){
			for each(var c:ProductTypeVO in clone){
				//Error found! both are new item, how to handle?!
				if(name == c.name && clone.getItemIndex(c) != _ds.getItemIndex(o)){
					//duplicate name
					myError = ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"error.common.duplicateKey",[name]);
					dg.editedItemPosition = {columnIndex:1, rowIndex: _ds.getItemIndex(o)};
					hasError = true;
					break;
				}else if (code == c.code && clone.getItemIndex(c) != _ds.getItemIndex(o)){
					//duplicate code
					myError = ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"error.common.duplicateKey",[code]);
					dg.editedItemPosition = {columnIndex:0, rowIndex: _ds.getItemIndex(o)};
					hasError = true;
					break;
				}
			}
		}
		
		if(hasError){

			showVerticalMiddleErrorTipAt(myError, dg);
			return false;
		}
	}
	return true;
}

